package com.controller;

import com.bean.Linker;
import com.service.file.StorageService;
import org.junit.runners.Parameterized;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Controller
@RequestMapping("file")
public class FileController {
    @Autowired
    StorageService storageService;

    @GetMapping("/")
    public String listUploadedFiles(Model model)throws IOException {
        List<Linker> linkers = storageService.loadAll().map(
                path -> new Linker(MvcUriComponentsBuilder.fromMethodName(FileController.class,
                        "serveFile", path.getFileName().toString()).build().toString(),
                        path.getFileName().toString())
        ).collect(Collectors.toList());

        model.addAttribute("linkers", linkers);
        return "index";
    }

    @GetMapping(value = "/files/{filename:.+}")
    @ResponseBody
    public ResponseEntity<?> serveFile(@PathVariable String filename) {
        ResponseEntity<?> body = null;
        try {
            Resource file = storageService.loadAsResource(filename);
            body = ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getFilename() + "\"").body(file);
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
            body = ResponseEntity.ok().body(e.getMessage());
        }
        return body;
    }
    @PostMapping(value = "/files/xxx")
    @ResponseBody
    public ResponseEntity<?> serveFile1(@RequestBody Map<String, String> map) {
        ResponseEntity<?> body = null;
        try {
            String fileName = map.get("fileName");
            Resource file = storageService.loadAsResource(fileName);
            body = ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getFilename() + "\"").body(file);
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
            body = ResponseEntity.ok().body(e.getMessage());
        }
        return body;
    }

    @PostMapping(value = "/files/xxxx")
    public ResponseEntity<?> serveFile12(Map<String, String> map) {
        ResponseEntity<?> body = null;
        try {
            String fileName = map.get("fileName");
            if (fileName == null) {
                fileName = "controller_ (49)";
            }
            Resource file = storageService.loadAsResource(fileName);
            body = ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getFilename() + "\"").body(file);
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
            body = ResponseEntity.ok().body(e.getMessage());
        }
        return body;
    }
    @GetMapping(value = "/filess/{filename:.+}")
    public ResponseEntity<byte[]> downloadsEntity(@PathVariable String filename) throws Exception{
//        String	path = "C:/";
//        String  fileName = "default.png";
//        File file=new File(path,fileName);
        Resource resource = storageService.loadAsResource(filename);
        File file = resource.getFile();
        if(!file.isFile()){
            return null;
        }
        @SuppressWarnings("resource")
        InputStream input=new FileInputStream(file);
        byte[] buff=new byte[input.available()]; // 获取文件大小
        input.read(buff) ;
        HttpHeaders headers=new HttpHeaders();
        headers.add("Content-Disposition", "attachment;filename="+filename);
        HttpStatus status=HttpStatus.OK;
        ResponseEntity<byte[]> entity=new ResponseEntity<>(buff,headers,status);
        return  entity;
    }

    @PostMapping("/")
    public String handleFileUpload(@RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes) {

        storageService.store(file);
        redirectAttributes.addFlashAttribute("message",
                "You successfully uploaded " + file.getOriginalFilename() + "!");

        return "redirect:/file/";
    }

//    @ExceptionHandler(StorageFileNotFoundException.class)
//    public ResponseEntity<?> handleStorageFileNotFound(StorageFileNotFoundException exc) {
//        return ResponseEntity.notFound().build();
//    }
}
